package com.hcloud.audit.api.service;

import com.hcloud.audit.api.bean.LoginLogBean;
import com.hcloud.audit.api.event.LoginLogEvent;
import com.hcloud.audit.api.util.IPUtils;
import com.hcloud.common.core.util.SpringUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Auther hepangui
 * @Date 2018/11/20
 */
@Service
public class LoginLogService {
    public  void saveLoginLog(String username,boolean success){
        LoginLogBean bean = new LoginLogBean();
        bean.setCreateTime(new Date());
        bean.setUsername(username);
        bean.setSuccess(success?1:0);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        bean.setIpAddr(IPUtils.getIpAddr(request));
        try{
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
            bean.setBrowser(userAgent.getBrowser().getName());
            bean.setDevice(userAgent.getOperatingSystem().getName());
            bean.setOsName(userAgent.getOperatingSystem().getDeviceType().getName());
        }catch (Exception e){}
        SpringUtil.publishEvent(new LoginLogEvent(bean));
    }
}
